#! /usr/bin/env python

import subprocess, multiprocessing

def sizeof_fmt(num):
    for x in ['B','KB','MB','GB','TB']:
        if num < 1024.0:
            return "%3.f%s" % (num, x)
        num /= 1024.0


CPUs = multiprocessing.cpu_count()
cases = [('0', '0'), ('1', '1'), ('0', '1'), ('0', '2'), ('0', str(CPUs - 1))]
results = {}

print "CPUs = ", CPUs, "Measuring...."
for f,t in cases:
    case = "Measured on %s, allocated on %s" % (f, t)
    print case,
    process = subprocess.Popen(['bin/mem_latency', '-c', '-s 64M', '-f', f, '-t', t], stdout=subprocess.PIPE)
    stdout, stderr = process.communicate()
    results[case] = stdout
    sz,latency,deviation = stdout.splitlines()[-1].split(',')
    print sizeof_fmt(int(sz)), 'latency %s(%s)' % (latency, deviation), 'ns'

    
    
import StringIO, numpy as np, pylab as pl

pl.figure(figsize = (14, 8))

for case, result in results.iteritems():
    a = np.loadtxt(StringIO.StringIO(result), skiprows=2, delimiter = ',')
    pl.errorbar(x = a[:, 0], y = a[:, 1], yerr = a[:, 2], label = case)

pl.xscale('log')
pl.grid()
pl.xticks(a[:,0], [sizeof_fmt(sz) for sz in a[:, 0]])
pl.yticks(range(0, 200, 5))
pl.xlabel("Working set")
pl.ylabel("Latency, nanoseconds")
pl.legend(loc = 'upper left')
pl.show()
